package com.sina.interfaces.core.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;

import java.io.*;

/**
 * created  on 06/06/2017.
 */
public abstract class FileUtils {

    private static final Logger LOG = LoggerFactory.getLogger(FileUtils.class);

    private FileUtils() {

    }

    /**
     * 读取指定位置的文件 的文本内容
     * @param pattern 路径模式
     * @return 内容,not null,则文件没有找到则返回 空串
     */
    public static String getTextContent(String pattern){
         String content ;
        try(InputStream in = new FileInputStream(ResourceUtils.getFile(pattern));ByteArrayOutputStream out = new ByteArrayOutputStream()){
            int len;
            byte[] buffer = new byte[1024];
            while ((len = in.read(buffer)) > 0){
                out.write(buffer,0,len);
            }
            content = new String(out.toByteArray(), Constant.CHARSET_UTF8);
        } catch ( IOException e) {
             content = "";

        }
        return content;
    }

    public static void createFile(File file) {
        try {
            if (!file.exists() && !file.createNewFile()) {
                if (file.exists()) {
                    LOG.debug("file[{}] is created by other thread", file);
                } else {
                    LOG.error("file[{}] create failure.", file);
                }
            }
        } catch (IOException e) {
            LOG.error("file[{}]", file, e);
        }
    }

    /**
     * 去除 前缀的 slope {@code /}
     */
    public static String dropPrefixSlope(String path) {
        String result = path;
        if (path.startsWith("/")) {
            int len = path.length();
            char ch;
            for (int i = 1; i < len; i++) {
                ch = path.charAt(i);
                if (ch != '/') {
                    result = path.substring(i);
                    break;
                }
            }
        }
        return result;
    }


    public static void deleteFile(File file) {
        if (file != null && !file.delete()) {
            LOG.warn("delete file[{}] failure", file);
        }
    }

    public static String getFileExtension(String fileName) {
        int index = fileName.lastIndexOf('.');
        String extension;
        if (index > 0) {
            extension = fileName.substring(index);
        } else {
            extension = "";
        }
        return extension;
    }


}
